package com.efounder.chat.activity;

import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.Toast;

import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.efounder.chat.R;
import com.efounder.chat.adapter.PoiAdapter;
import com.efounder.chat.model.PoiLocation;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.utilcode.util.StatusBarUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 高德搜索地点
 * @author zhaojiakun
 */
public class SearchLocationActivity extends BaseActivity implements Inputtips.InputtipsListener, AdapterView.OnItemClickListener {

    private ArrayList<PoiLocation> poiList;
    private PoiAdapter adapter;
    private AutoCompleteTextView etSearch;
    private ListView lv;
    private SmartRefreshLayout smartRefreshLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_location);

        init();
    }

    @Override
    protected void setStatusBarFontColor() {
        StatusBarUtil.setLightMode(this);
    }

    private void init() {
//        LinearLayout llBack = (LinearLayout) findViewById(R.id.leftbacklayout);
//        ImageView backBtn = (ImageView) findViewById(R.id.backButton);
//        TextView tvTitle = (TextView) findViewById(R.id.fragmenttitle);
        lv = (ListView) findViewById(R.id.lv_poi);
        smartRefreshLayout = (SmartRefreshLayout) findViewById(R.id.refreshLayout);
//        if (null!=llBack)
//        llBack.setVisibility(View.VISIBLE);
//        tvTitle.setText("位置");
        poiList = new ArrayList<>();
        adapter = new PoiAdapter(this, poiList, "search");
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(this);
        //只允许下拉刷新
        smartRefreshLayout.setEnableLoadMore(true);
        smartRefreshLayout.setEnableRefresh(true);
        smartRefreshLayout.setOnRefreshListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                lv.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshLayout.finishLoadMore();
                        Toast.makeText(SearchLocationActivity.this, R.string.wrchatview_not_have_more_data, Toast.LENGTH_LONG).show();
                    }
                }, 1000);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                lv.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        String s = etSearch.getText().toString();
                        inputTips(s);
                        smartRefreshLayout.finishRefresh();
                    }
                }, 1000);
            }
        });

        etSearch = (AutoCompleteTextView) findViewById(R.id.et_search);

        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                inputTips(s.toString());
            }
        });

    }

    private void inputTips(String s) {
        //第二个参数传入null或者“”代表在全国进行检索，否则按照传入的city进行检索
        InputtipsQuery inputquery = new InputtipsQuery(s, null);
        inputquery.setCityLimit(false);//限制在当前城市
        Inputtips inputTips = new Inputtips(SearchLocationActivity.this, inputquery);
        inputTips.setInputtipsListener(SearchLocationActivity.this);
        inputTips.requestInputtipsAsyn();
    }

    @Override
    public void onGetInputtips(List<Tip> tipList, int rCode) {
        poiList.clear();
        //通过tipList获取Tip信息
        if (rCode == 1000) {
            String tp = "";
            if (tipList != null && tipList.size() > 0) {
                for (int i = 0; i < tipList.size(); i++) {
                    Tip tip = tipList.get(i);
                    String name = tip.getName();
                    String address = tip.getAddress();
                    LatLonPoint point = tip.getPoint();
                    if(point == null){
                        continue;
                    }
                    double latitude = point.getLatitude();
                    double longitude = point.getLongitude();
                    String district = tip.getDistrict();
                    PoiLocation location = new PoiLocation();
                    if (!TextUtils.isEmpty(name))
                        location.setTitle(name);
                    if (!TextUtils.isEmpty(district+address))
                        location.setAddress(district + address);
                    location.setLatitude(latitude);
                    location.setLongitude(longitude);
                    poiList.add(location);
                    tp += ",name=" + name + ",address=" + district + address + ",point=" + point.toString();
                }
                Log.e("onGetInputtips", "tp=" + tp + ",currentThread=" + Thread.currentThread().getName());

            }
        }
        adapter.notifyDataSetChanged();
        smartRefreshLayout.finishRefresh();
    }

    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.tv_search_cancel) {
            setResult(RESULT_OK);
            finish();
        }else if (i==R.id.backButton){
            setResult(RESULT_OK);
            finish();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent();
        double latitude = poiList.get(position).getLatitude();
        double longitude = poiList.get(position).getLongitude();
        Bundle bundle = new Bundle();
        bundle.putDouble("lat", latitude);
        bundle.putDouble("lng", longitude);
        intent.putExtras(bundle);
        setResult(RESULT_OK, intent);
        finish();
    }
}
